'use strict';

/**
 * @ngdoc function
 * @name afasApp.controller:BanktransferrecordCtrl
 * @description
 * # BanktransferrecordCtrl
 * Controller of the afasApp
 */

angular.module('afasApp')
  .controller('BanktransferrecordsCtrl', ['$scope', '$state', 'Services', '$filter', function ($scope, $state, Services, $filter) {

    // $scope.banktransferrecords = [];
    $scope.banktransferrecords = [];
    $scope.banks = [];
    $scope.newItem = {};
    $scope.params = {
      keyword: $scope.searchText
    };
    $scope.errors = {};

    // PAGINATION
    $scope.pagesize = 10;

    $scope.pagination = {
      current: 1
    };

    $scope.pageChanged = function(newPage) {
      getResultsPage(newPage);
    };

    function getResultsPage(pageNumber) {
      var data = $scope.params;
      data.pagesize = $scope.pagesize;
      data.page = (pageNumber - 1);
      $scope.pagination.current = pageNumber;
      Services.getItems('bank_transfers', data)
      .then(function( results ) {
        var pagingData = angular.fromJson(results.headers['x-pagination']);
        $scope.totalItems = pagingData.TotalCount;
        $scope.banktransferrecords = results.data;
      });
    }
    getResultsPage(1);

    Services.getItems('banks')
    .then(function(results){
      $scope.banks = results.data;
    });

    $scope.add = function () {
      // console.log($scope.newItem);
      $scope.errors = {};
      $scope.newItem.Date = $filter('date')($scope.timepicker.timeA, 'yyyy-MM-dd HH:mm:ss');
      Services.add($scope.BANKTRANSFER_URL, $scope.newItem)
      .then(function(results){
        // console.log(results);
        $scope.newItem = {};
        $state.go( 'banktransferrecords.list' );
      }, function(results){
        if (results.status == 400) {
          $scope.errors = results.data;
        }
      });
    };

    $scope.delete = function (item) {
      Services.delete($scope.BANKTRANSFER_URL, item);
    };
  }])
  .controller('BanktransferrecordCtrl', ['$scope', 'Services', '$state', '$stateParams', function ($scope, Services, $state, $stateParams) {

    $scope.current = {};
    $scope.banks = [];
    $scope.currentID = $stateParams.id;
    $scope.current = {};

    Services.getItem($scope.BANKTRANSFER_URL, $stateParams.id)
    .then(function(results){
      $scope.current = results.data;
      $scope.current.Date = $filter('date')($scope.current.Date, 'yyyy-MM-dd HH:mm:ss');
    });

    Services.getItems('banks')
    .then(function(results){
      $scope.banks = results.data;
    });

    $scope.update = function () {
      $scope.current.Date = $filter('date')($scope.current.Date, 'yyyy-MM-dd HH:mm:ss');
      Services.update($scope.BANKTRANSFER_URL, $scope.current, $scope.currentID)
      .then(function(results){
        $state.go( 'banktransferrecords.show', {id: $scope.currentID} );
      });
    };
  }]);
